package com.shenmazong.serveruserapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenmazong.TbNo;
import com.shenmazong.serveruserapi.mapper.ITbNoMapper;
import com.shenmazong.serveruserapi.service.TbNoService;
import com.shenmazong.serveruserapi.util.GoodNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TbNoServiceImpl implements TbNoService {

    @Autowired
    private ITbNoMapper iTbNoMapper;

    /**
     * 获取空闲用户编号
     * @return
     */
    @Override
    public Integer getFreeUserNoCount() {
        Integer status = iTbNoMapper.selectCount(
                new QueryWrapper<TbNo>().eq("status", 0)
        );
        return status;
    }

    /**
     * 获取最大用户编号
     * @return
     */
    @Override
    public Integer getMaxUserNo() {
        TbNo userno = iTbNoMapper.selectOne(
                new QueryWrapper<TbNo>().orderByDesc("userno").last("limit 1")
        );

        if(userno == null) {
            return 0;
        }

        return userno.getUserno();
    }

    @Override
    public void addUserNo(Integer userNo) {

        TbNo tbNo = new TbNo();
        tbNo.setUserno(userNo);
        tbNo.setStatus(0);

        if(GoodNumber.isGoodNum(userNo))
            tbNo.setStatus(2);

        iTbNoMapper.insert(tbNo);
    }

    @Override
    public List<TbNo> getFreeUserNo() {
        return iTbNoMapper.selectList(new QueryWrapper<TbNo>().eq("status", 0).last("limit 20"));
    }

    @Override
    public void setUserNoUsing(Integer id, Integer code) {
        TbNo tbNo = new TbNo();
        tbNo.setId(id);
        tbNo.setUserno(code);
        tbNo.setStatus(1);
        iTbNoMapper.updateById(tbNo);
    }
}
